package com.example.controller;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.annotation.Log;
import com.example.common.result.Result;
import com.example.entity.dto.IHeadDTO;
import com.example.entity.dto.Pojo;
import com.example.entity.dto.PojoDto;
import com.example.entity.dto.inspect.*;
import com.example.entity.hz.IBasics;
import com.example.entity.hz.IBody;
import com.example.entity.hz.IHead;
import com.example.entity.hz.MOCTA;
import com.example.entity.vo.MocVo;
import com.example.entity.vo.SaveInspectResultVo;
import com.example.entity.vo.inspect.InspectionItemInfo;
import com.example.entity.vo.inspect.ProductInspectionItemListVo;
import com.example.entity.vo.pc.MoctyPlus;
import com.example.entity.yifei.*;
import com.example.enums.InspectStatusEnum;
import com.example.enums.MOCStatusEnum;
import com.example.enums.MachineStatusEnum;
import com.example.exception.CustomException;
import com.example.mapper.*;
import com.example.service.*;
import com.example.service.impl.ActFlowCommService;
import com.example.service.pc.ResourceService;
import com.example.service.pc.ResourcegroupService;
import com.example.untils.BeanUtils;
import com.example.untils.SecurityUtils;
import com.example.untils.StringUtils;
import com.example.untils.TimeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

@CrossOrigin // 解决跨域
@RestController
@RequestMapping("/api/Qmsmg")
@Api(tags = "检验前端控制器")
public class QmsmgController {
    @Resource
    private ActFlowCommService actFlowCommService;
    @Resource
    private CmsmdService cmsmdService;
    @Resource
    private CmsmxService cmsmxService;
    @Resource
    private NgreasonService ngreasonService;
    @Resource
    private IHeadService iHeadService;
    @Autowired
    private MoclogService moclogService;
    @Resource
    private IBodyService iBodyService;
    @Resource
    private IBasicsMapper iBasicsMapper;
    @Resource
    private InspectionngService inspectionngService;
    @Resource
    private MoctaMapper moctaMapper;
    @Autowired
    private InspectiontimeMapper inspectiontimeMapper;

    @Resource
    private SFCTEService sfcteService;
    @Resource
    private QmsmgService qmsmgService;
    @Resource
    private InvmbService invmbService;
    @Resource
    private CmsmwService cmsmwService;

    @Resource
    private QmsmgMapper qmsmgMapper;

    @Resource
    private MoctyService moctyService;

    @Resource
    private MoctyMapper moctyMapper;

    @Resource
    private ResourcegroupService resourcegroupService;

    @Resource
    private ResourceService resourceService;

    @PostMapping("/update")
    @ApiOperation("修改品号检验项目")
    public Result update(@RequestBody Qmsmg qmsmg){
        return this.qmsmgService.update(qmsmg);
    }

    @GetMapping("/delete")
    @ApiOperation("通过品号和检验编号删除品号检验项目")
    public Result delete(String mg002,String mg003){
        return this.qmsmgService.delete(mg002,mg003);
    }

    @GetMapping("/queryXq")
    @ApiOperation("通过品号和检验编号查询详细信息,便于修改")
    public Result<Qmsmg> queryXq(String mg002,String mg003){
        return this.qmsmgService.queryXq(mg002,mg003);
    }

    @PostMapping("queryInvmb")
    @ApiOperation("分页查询品号信息")
    public Result<Map<String, Invmb>> queryInvmb(@RequestBody PojoDto pojoDto){
        return invmbService.query(pojoDto);
    }

    @PostMapping("queryCmsmw")
    @ApiOperation("分页查询工艺信息")
    public Result<Map<String, Cmsmw>> queryCmsmw(@RequestBody PojoDto pojoDto){
        return cmsmwService.query(pojoDto);
    }

    @PostMapping("addqmsmg")
    @ApiOperation("新增检验项目")
    public Result addqmsmg(@RequestBody List<Qmsmg> qmsmgList){
       return this.qmsmgService.insert(qmsmgList);
    }

    @PostMapping("queryIPage")
    @ApiOperation("分页查询品号检验项目")
    public Result<Map<String,Qmsmg>> queryIPage(@RequestBody PojoDto pojo){
        return this.qmsmgService.queryPage(pojo);
    }

    @PostMapping("test")
    @ApiOperation("测试修改")
    public Result test(String code){
        return this.sfcteService.test(code);
    }

    @ApiOperation("检验单通过品号进行查询")
    @PostMapping("/queryList")
    public Result query(@RequestBody Pojo pojo){
        return this.sfcteService.queryById(pojo);
    }

    @ApiOperation("新增检验结果")
    @PostMapping("/add")
    public Result add(@RequestBody IHeadDTO iHeadDTO){
        System.out.println(iHeadDTO.toString());
        iHeadService.add(iHeadDTO);
        return Result.ok();
    }

    @ApiOperation("新增检验项目")
    @PostMapping("/insProductInspectItem")
    @DSTransactional
    public Result insProductInspectItem(@RequestBody InsProductInspectItemDto dto) {

        List<Qmsmg> qmsmgList = new ArrayList<>();
        for(InsertQmsmgDto t : dto.getItemList()) {
            Qmsmg qmsmg = new Qmsmg();
            BeanUtils.copyPropertiesIgnoreCase(t, qmsmg);
            qmsmg.setCREATOR(SecurityUtils.getLoginUser().getUsername());
            qmsmg.setCREATE_DATE(TimeUtils.getNowTime());
            qmsmg.setMG001(qmsmg.getMG003());
            qmsmg.setMG010("Y");
            qmsmg.setMG011("3");
            qmsmg.setMG015("1");
            qmsmg.setMG016(new BigDecimal(0));
            qmsmg.setMG017("N");
            qmsmgList.add(qmsmg);
        }

        for(String product : dto.getProductIdList()) {
            Invmb invmb = invmbService.getOne(new LambdaQueryWrapper<Invmb>().eq(Invmb::getMb001, product));
            if(invmb == null) {
                throw new CustomException("500", "品号：" + product.trim() + "不存在.");
            }
            for(String mg020 : dto.getTypeList()) {
                for(Qmsmg qmsmg : qmsmgList) {
                    qmsmg.setMG020(mg020);
                    qmsmg.setMG002(product);
                    qmsmg.setUDF10(invmb.getMb002());
                    qmsmg.setUDF11(invmb.getMb003());
                    Integer count = qmsmgMapper.selectCount(new LambdaQueryWrapper<Qmsmg>()
                            .eq(Qmsmg::getMG002, product).eq(Qmsmg::getMG020, mg020).eq(Qmsmg::getMG001, qmsmg.getMG001()));
                    if(count != null && count > 0) {
                        throw new CustomException("500", "品号：" + product.trim() + "已有" + mg020 + "的检验项目编号为: " + qmsmg.getMG001());
                    }
                    qmsmgMapper.insert(qmsmg);
                }
            }
        }
        return Result.ok();
    }

    @ApiOperation("导入Excel格式检查")
    @PostMapping("/checkExcel")
    public Result checkExcel(@RequestPart(value = "files") MultipartFile file,HttpServletResponse response) throws Exception {
        return qmsmgService.checkExcel(file,response);
    }

    @ApiOperation("Excel表格数据导入接口")
    @PostMapping("/getExcels")
    public Result getExcels(@RequestPart(value = "files") MultipartFile file,HttpServletResponse response, @RequestParam("zhi") String zhi) throws Exception {
       return qmsmgService.getExcels2(file,response, zhi);
    }

    @ApiOperation("导出Excel(首检，巡检)")
    @PostMapping("/exportExcel")
    public Result exportExcel() throws Exception {
        return qmsmgService.exportExcel();
    }

    @ApiOperation("检验单详情删除")
    @GetMapping("/del")
    public Result del(Long id){
        return iHeadService.del(id);
    }

    @DSTransactional
//    @ApiOperation("新增首检单")     现场/实验室
//    @PostMapping("/addFirstInspection")
    public Result addFirstInspection(@RequestBody AddFirstInspectionDto dto) {
        MoctyPlus moctyPlus = moctyMapper.getMoctyPlus(dto.getUuid());
        if(moctyPlus == null) {
            throw new CustomException("500", "排产记录未找到");
        }
        if("****".equals(moctyPlus.getTy009().trim())) {
            throw new CustomException("500", "未分配到具体机器，请先分配");
        }
        if(StringUtils.isEmpty(moctyPlus.getTy009().trim())) {
            throw new CustomException("500", "没有机器");
        }
        // TODO 不是待首检的话，就不能生成首检单
        if(!MOCStatusEnum.DaiShouJian.getValue().equals(moctyPlus.getUdf01().trim())) {
            throw new CustomException("500", "排产单据不在" + MOCStatusEnum.DaiShouJian.getValue() + "状态");
        }

        QueryWrapper<Qmsmg> qmsmgQueryWrapper = new QueryWrapper<>();
        qmsmgQueryWrapper.eq("MG002", moctyPlus.getProductId());// 品号
        qmsmgQueryWrapper.eq("MG020", "首检"); //检验项目
        qmsmgQueryWrapper.eq("MG008", moctyPlus.getProcessId()); // 区分工艺
        qmsmgQueryWrapper.last("AND UDF06 IS NOT NULL AND UDF06 != ''");
//        if (!StringUtils.isBlank(pojo.getRomm())){
//            qmsmgQueryWrapper.eq("UDF06", pojo.getRomm()); // 场地
//        }
        List<Qmsmg> qmsmgs = qmsmgMapper.selectList(qmsmgQueryWrapper);
        if (qmsmgs.isEmpty()) {  //没有首检项目，可直接上机
            Mocty mocty = new Mocty();  mocty.setUdf01(MOCStatusEnum.DaiJinZhan.getValue());
            moctyMapper.update(mocty, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUuid()));
            return Result.success("该品号工艺没有首检项目, 可直接上机。", "该品号工艺没有首检项目, 可直接上机。");
        }

//        DynamicDataSourceContextHolder.push("mes");
        com.example.entity.mysql.Resource resource = resourceService.getOne(new LambdaQueryWrapper<com.example.entity.mysql.Resource>()
                .eq(com.example.entity.mysql.Resource::getResourceGroupIdIsF, moctyPlus.getTy009()));
        if(resource == null) {
            throw new CustomException("500", "机器不存在");
        }
        if(resource.getStatus() == null || !MachineStatusEnum.XianZhi.getValue().equals(resource.getStatus().trim())) {
            throw new CustomException("500", "机器不在" + MachineStatusEnum.XianZhi.getValue() + "状态");
        }

//        DynamicDataSourceContextHolder.push("demo");
        Map<String, List<Qmsmg>> map = new HashMap<>();
        for(Qmsmg t : qmsmgs) {
            List<Qmsmg> qmsmgList = map.get(t.getUDF06().trim());
            if(qmsmgList == null) qmsmgList = new ArrayList<>();
            qmsmgList.add(t);
            map.put(t.getUDF06().trim(), qmsmgList);
        }
        List<IHead> iHeadList = new ArrayList<>();
        List<IBody> iBodyList = new ArrayList<>();
//        Integer order = qmsmgMapper.orderByUUid(dto.getUuid());
        for (Map.Entry<String, List<Qmsmg>> entry : map.entrySet()) {
            IHead iHead = new IHead();
            iHead.setType("SJ");
            iHead.setUid(qmsmgMapper.uid());
            iHead.setTa001(moctyPlus.getTy001());
            iHead.setTa002(moctyPlus.getTy002());
            iHead.setTa004(moctyPlus.getProcessId());
            iHead.setTa024(moctyPlus.getProcessName());
            iHead.setTa006(moctyPlus.getProductId());
            iHead.setMb002(moctyPlus.getProductName());
            iHead.setMb003(moctyPlus.getSpecification());
            iHead.setTa015(new BigDecimal(moctyPlus.getTy004()));
            iHead.setCreatTime(TimeUtils.getFullNowTime());
            iHead.setUdf66(new BigDecimal(3D));
//            iHead.setOrderNum(order);
//        iHead.setUdf88(new BigDecimal(3D));
            iHead.setMoctyudf05(dto.getUuid());
            iHead.setStatus(InspectStatusEnum.DaiJianYan.getValue());
            iHead.setUdf06(entry.getKey());
            iHead.setMacNo(resource.getDeviceid());
            iHead.setMacName(resource.getDevicename());
            iHead.setWorkCenterID(moctyPlus.getWorkCenterId());
            iHead.setWorkCenterName(moctyPlus.getWorkCenterName());
            iHead.setCreator("ERP");
            Cmsmx cmsmx = cmsmxService.getOne(new LambdaQueryWrapper<Cmsmx>().eq(Cmsmx::getMx001, resource.getDeviceid()));
            iHead.setMacPlaceID(cmsmx.getMx002());
            Cmsmd cmsmd = cmsmdService.getOne(new LambdaQueryWrapper<Cmsmd>().eq(Cmsmd::getMd001, cmsmx.getMx002()));
            iHead.setMacPlaceName(cmsmd.getMd002());
            iHead.setApprovalCode("N");
            iHead.setStatusCode("0");
            iHeadList.add(iHead);

            List<Qmsmg> list = entry.getValue();
            for(Qmsmg item : list) {
                IBody iBody = new IBody();
                iBody.setI_uid(iHead.getUid());
                BeanUtils.copyPropertiesIgnoreCase(item, iBody);
                iBodyList.add(iBody);
            }
//            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
        iHeadService.saveBatch(iHeadList);
        iBodyService.saveBatch(iBodyList);
        Mocty mocty = new Mocty();
        mocty.setModiDate(TimeUtils.getNowTime());
        mocty.setModifier("ERP");
        mocty.setUdf01(MOCStatusEnum.ShouJianZhong.getValue());
//        mocty.setUdf02(order.toString());
        moctyMapper.update(mocty, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUuid()));
        return Result.success();
    }

    @ApiOperation("检验列表")
    @PostMapping("/inspectionList")
    public Result<PageInfo<List<IHead>>> inspectionList(@RequestBody InspectionListDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize(), "creatTime DESC");
        LambdaQueryWrapper<IHead> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(dto.getStatus())) wrapper.eq(IHead::getStatus, dto.getStatus());
        if(StringUtils.isNotEmpty(dto.getType())) wrapper.eq(IHead::getType, dto.getType());
        if(StringUtils.isNotEmpty(dto.getMacNo())) wrapper.eq(IHead::getMacNo, dto.getMacNo());
        if(StringUtils.isNotEmpty(dto.getJinzhanUuid())) wrapper.eq(IHead::getJinzhanUuid, dto.getJinzhanUuid());
        if(StringUtils.isNotEmpty(dto.getUid())) wrapper.eq(IHead::getJinzhanUuid, dto.getUid());
        List<IHead> list = iHeadService.list(wrapper);
        PageInfo<List<IHead>> pageInfo = new PageInfo(list);
        return Result.success(pageInfo);
    }

    @ApiOperation("查看检验单详情")
    @PostMapping("/inspectDetail")
    public Result<MocVo> inspectDetail(@RequestBody InspectDetailDto dto) {
        IHead iHead = iHeadService.getOne(new LambdaQueryWrapper<IHead>().eq(IHead::getUid, dto.getUid()).eq(IHead::getType, dto.getType()));
        Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, iHead.getMoctyudf05()));
        MOCTA mocta = moctaMapper.selectOne(new LambdaQueryWrapper<MOCTA>().eq(MOCTA::getTA001, mocty.getTy001()).eq(MOCTA::getTA002, mocty.getTy002()));
        List<Qmsmg> qmsmgList = new ArrayList<>();
        List<IBody> bodies = iBodyService.list(new LambdaQueryWrapper<IBody>().eq(IBody::getI_uid, dto.getUid()));
        for(IBody t : bodies) {
            Qmsmg qmsmg = new Qmsmg();  BeanUtils.copyPropertiesIgnoreCase(t, qmsmg);
            qmsmgList.add(qmsmg);
        }
        MocVo mocVo = new MocVo();
        mocVo.setSingetsu(iHead.getTa001());
        mocVo.setOdd(iHead.getTa002());
        mocVo.setShijian(iHead.getCreatTime());
        mocVo.setSbm(iHead.getMacNo());
        mocVo.setMacName(iHead.getMacName());
        mocVo.setGx(mocty.getTy019());
        mocVo.setPinhao(iHead.getTa006());
        mocVo.setGy(iHead.getTa004());
        mocVo.setGyName(iHead.getTa024());
        mocVo.setGg(iHead.getMb003());
        mocVo.setPm(iHead.getMb002());
        mocVo.setJy(iHead.getUdf06());
        mocVo.setZx(mocta.getTA021());
        mocVo.setScx(iHead.getMacName());
        mocVo.setStatus(iHead.getStatus());

        qmsmgList.sort(new Comparator<Qmsmg>() {
            @Override
            public int compare(Qmsmg o1, Qmsmg o2) {
                return o1.getMG003().compareTo(o2.getMG003());
            }
        });
        mocVo.setQmsmgList(qmsmgList);

        return Result.success(mocVo);
    }

    @Log("保存检验单的检验结果")
    @ApiOperation("保存检验单的检验结果")
    @PostMapping("/saveInspectResult")
    @DSTransactional
    public Result saveInspectResult(@RequestBody SaveInspectResultDto dto) {
        if(StringUtils.isEmpty(dto.getStatus())) {
            throw new CustomException("500", "检验结果不能为空");
        }
        IHead one = iHeadService.getOne(new LambdaQueryWrapper<IHead>().eq(IHead::getUid, dto.getUid()));
        if(one == null) {
            throw new CustomException("500", "检验编号不存在");
        }
        if(!InspectStatusEnum.DaiJianYan.getValue().equals(one.getStatus().trim())) {
            throw new CustomException("500", "已有检验结果, 不能保存");
        }
        IHead iHead = new IHead();
        iHead.setPeople(dto.getPeople());
        iHead.setPeopleName(dto.getPeopleName());
        iHead.setStatus(dto.getStatus());
        iHead.setUdf66(dto.getUdf66());
        iHead.setUdf88(dto.getUdf88());
        iHeadService.update(iHead, new LambdaQueryWrapper<IHead>().eq(IHead::getUid, dto.getUid()));
//        List<IBody> iBodyList = new ArrayList<>();
        for(IBasicsDto t : dto.getBasicsList()) {
            IBasics iBasics = new IBasics();
            BeanUtils.copyPropertiesIgnoreCase(t, iBasics);
            iBasicsMapper.insert(iBasics);
            if(t.getNgList() != null) {
                for(Inspectionng item : t.getNgList()) {
                    item.setI_uid(iBasics.getUid());
                }
            }
            if(t.getNgList() != null && t.getNgList().size() > 0) inspectionngService.saveBatch(t.getNgList());
        }
        Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, one.getMoctyudf05()));
        if(mocty == null) {
            throw new CustomException("500", "排产订单不存在");
        }

        Moclog moclog = new Moclog();
        moclog.setTa001(mocty.getTy001());
        moclog.setTa002(mocty.getTy002());
        moclog.setMoctyudf05(mocty.getUdf05());

        moclog.setCreator(SecurityUtils.getLoginUser().getUsername());
        moclog.setCreatetime(TimeUtils.getFullNowTime());
        moclog.setMacno(one.getMacNo());
        moclog.setMacname(one.getMacName());
        moclog.setInspectionid(dto.getUid());
        moclog.setInspectiontype(dto.getType());

        if(InspectStatusEnum.OK.getValue().equals(dto.getStatus())) {
            if("SJ".equals(one.getType().trim())) {
                Inspectiontime time = new Inspectiontime();
                time.setMoctyudf05(mocty.getUdf05()); time.setJinzhanuuid(one.getJinzhanUuid()); time.setInspectiontime(TimeUtils.getNowTime());
                time.setMacNo(one.getMacNo());  time.setMacName(one.getMacName());
                time.setWorkCenterID(one.getWorkCenterID());  time.setWorkCenterName(one.getWorkCenterName());
                time.setMacPlaceID(one.getMacPlaceID());  time.setMacPlaceName(one.getMacPlaceName());
                inspectiontimeMapper.insert(time);
            }
//            com.example.entity.mysql.Resource resource = resourceService.getOne(new LambdaQueryWrapper<com.example.entity.mysql.Resource>().eq(com.example.entity.mysql.Resource::getMoctyudf05, one.getMoctyudf05()));
//            if(resource != null) {
//                resource.setInspectionTime(TimeUtils.getNowTime());   yyyyMMddHHmmssSSS
//                resourceService.update(resource, new LambdaQueryWrapper<com.example.entity.mysql.Resource>().eq(com.example.entity.mysql.Resource::getMoctyudf05, one.getMoctyudf05()));
//            }
//            Mocty mocty1 = new Mocty();
//            mocty1.setUdf01(MOCStatusEnum.DaiJinZhan.getValue());
//            moctyMapper.update(mocty1, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, one.getMoctyudf05()));
            moclog.setRemark("检验单状态为OK, 检验成功");
//            moclog.setStatus(MOCStatusEnum.DaiJinZhan.getValue());
        }else{
            if("SJ".equals(one.getType().trim())) {
                Inspectiontime time = new Inspectiontime();
                time.setMoctyudf05(mocty.getUdf05()); time.setJinzhanuuid(one.getJinzhanUuid()); time.setInspectiontime(TimeUtils.getNowTime());
                time.setMacNo(one.getMacNo());  time.setMacName(one.getMacName());
                time.setWorkCenterID(one.getWorkCenterID());  time.setWorkCenterName(one.getWorkCenterName());
                time.setMacPlaceID(one.getMacPlaceID());  time.setMacPlaceName(one.getMacPlaceName());
                inspectiontimeMapper.insert(time);
            }
//            Mocty mocty1 = new Mocty();
//            mocty1.setUdf01(MOCStatusEnum.DaiShouJian.getValue());
//            moctyMapper.update(mocty1, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, one.getMoctyudf05()));
            moclog.setRemark("检验单状态为NG, 检验失败");
//            moclog.setStatus(MOCStatusEnum.DaiShouJian.getValue());
        }
        moclogService.save(moclog);
        return Result.success("检验结果保存成功" + new SaveInspectResultVo(one.getUid().toString()));
    }

    @ApiOperation("NG原因列表")
    @GetMapping("/ngReasonList")
    public Result<List<Ngreason>> ngReasonList() {
        List<Ngreason> list = ngreasonService.list();
        list.sort(new Comparator<Ngreason>() {
            @Override
            public int compare(Ngreason o1, Ngreason o2) {
                if(!o1.getNgtype().equals(o2.getNgtype())) return o1.getNgtype().compareTo(o2.getNgtype());
                return new Integer(o1.getNgno().substring(1)).compareTo(new Integer(o2.getNgno().substring(1)));
            }
        });
        return Result.success(list);
    }

    @ApiOperation("品號檢驗項目列表")
    @PostMapping("/productInspectionItemList")
    public Result<PageInfo<List<ProductInspectionItemListVo>>> productInspectionItemList(@RequestBody ProductInspectionItemListDto dto) {
        if(StringUtils.isEmpty(dto.getInspectionType())) {
            throw new CustomException("500", "检验类型不能为空");
        }
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<ProductInspectionItemListVo> res = qmsmgMapper.productInspectionItemList(dto);
        List<String> list = new ArrayList<>();
        for(ProductInspectionItemListVo t : res) list.add(t.getProductId());
        List<InspectionItemInfo> itemInfoList = qmsmgMapper.getItemInfo(list);

        Map<String, List<InspectionItemInfo>> map = new HashMap<>();
        for(InspectionItemInfo t : itemInfoList) {
            List<InspectionItemInfo> itemInfos = map.get(t.getMG002().trim());
            if(itemInfos == null) itemInfos = new ArrayList<>();
            itemInfos.add(t);
            map.put(t.getMG002().trim(), itemInfos);
        }
        PageInfo<List<ProductInspectionItemListVo>> pageInfo = new PageInfo(res);
        for(ProductInspectionItemListVo t : res) {
            t.setItemInfoList(map.get(t.getProductId().trim()));
        }

        return Result.success(pageInfo);
    }

    @ApiOperation("覆蓋品號檢驗項目")
    @PostMapping("/coverProductInspectionItem")
    @DSTransactional
    public Result coverProductInspectionItem(@RequestBody CoverProductInspectionItemDto dto) {

        for(CoverProductSonItem item : dto.getNeedToCoverList()) {
            for(String mg020 : item.getTypeList()) {
                qmsmgMapper.delete(new LambdaQueryWrapper<Qmsmg>().eq(Qmsmg::getMG002, item.getNeedToCoverProductId()).eq(Qmsmg::getMG020, mg020));
            }
        }
        // （首检，过程检验）拿目标品号的什么项目去覆盖
        List<Qmsmg> shouJian = qmsmgMapper.selectList(new LambdaQueryWrapper<Qmsmg>().eq(Qmsmg::getMG002, dto.getTargetProductId()).eq(Qmsmg::getMG020, "首检"));
        List<Qmsmg> xunJian = qmsmgMapper.selectList(new LambdaQueryWrapper<Qmsmg>().eq(Qmsmg::getMG002, dto.getTargetProductId()).eq(Qmsmg::getMG020, "过程检验"));
//        for(String mg020 : dto.getTypeList()) {
//            for(String mg002 : dto.getNeedToCoverList()) {
//                qmsmgMapper.delete(new LambdaQueryWrapper<Qmsmg>().eq(Qmsmg::getMG002, mg002).eq(Qmsmg::getMG020, mg020));
//            }
//        }
        List<Qmsmg> insertList = new ArrayList<>();
        for(CoverProductSonItem item : dto.getNeedToCoverList()) {
            Invmb invmb = invmbService.getOne(new LambdaQueryWrapper<Invmb>().eq(Invmb::getMb001, item.getNeedToCoverProductId()));
            for(String mg020 : item.getTypeList()) {
                if(mg020.trim().equals("首检")) {
                    for(Qmsmg t : shouJian) {
                        Qmsmg x = new Qmsmg();
                        BeanUtils.copyPropertiesIgnoreCase(t, x);
                        x.setMG020(mg020);
                        x.setMG002(item.getNeedToCoverProductId());
                        x.setUDF10(invmb.getMb002());  x.setUDF11(invmb.getMb003());
                        insertList.add(x);
                    }
                }else if(mg020.trim().equals("过程检验")) {
                    for(Qmsmg t : xunJian) {
                        Qmsmg x = new Qmsmg();
                        BeanUtils.copyPropertiesIgnoreCase(t, x);
                        x.setMG020(mg020);
                        x.setMG002(item.getNeedToCoverProductId());
                        x.setUDF10(invmb.getMb002());  x.setUDF11(invmb.getMb003());
                        insertList.add(x);
                    }
                }
            }
        }

//        for(String mg020 : dto.getTypeList()) {
//            List<Qmsmg> qmsmgList = qmsmgMapper.selectList(new LambdaQueryWrapper<Qmsmg>().eq(Qmsmg::getMG002, dto.getTargetProductId()).eq(Qmsmg::getMG020, mg020));
//            for(String mg002 : dto.getNeedToCoverList()) {
//                Invmb invmb = invmbService.getOne(new LambdaQueryWrapper<Invmb>().eq(Invmb::getMb001, mg002));
//                for(Qmsmg t : qmsmgList) {
//                    Qmsmg x = new Qmsmg();
//                    BeanUtils.copyPropertiesIgnoreCase(t, x);
//                    x.setMG002(mg002);  x.setUDF10(invmb.getMb002());  x.setUDF11(invmb.getMb003());
//                    insertList.add(x);
//                }
//            }
//        }
        qmsmgService.saveBatch(insertList);
        return Result.success();
    }


    @Log("上报检验单")
    @ApiOperation("上报检验单")
    @GetMapping("/report")
    @DSTransactional
    public Result report(
            @RequestParam String TC001, @RequestParam String TC002, @RequestParam String username, @RequestParam String leader
    ) {
        if (StringUtils.isEmpty(TC001) || StringUtils.isEmpty(TC002)) {
            return Result.error("单别或单号为空");
        }
        if (StringUtils.isEmpty(username)) {
            return Result.error("用户名为空");
        }
        String formkey = "qmsmg";
        String beanName = formkey + "ServiceImpl";
        ProcessInstance processInstance;
        String bussinessKey = formkey + ":" + TC001 + ":" + TC002;
        String id = TC001 + ":" + TC002;
        Boolean b = actFlowCommService.isOnly(bussinessKey, formkey);
        Boolean b2 = qmsmgService.tc30IsN(TC001, TC002);
        if (b && b2) {
            processInstance = actFlowCommService.startProcess(formkey, beanName, bussinessKey, id, username, leader);
        } else {
            return Result.error("有相同单据正在审核或该单据已审核完成");
        }
        //获取流程实例id
        String processInstanceId = processInstance.getId();
        List<Task> taskList = actFlowCommService.myTaskList(username);
        if (!CollectionUtils.isEmpty(taskList)) {
            for (Task task : taskList) {
                if (task.getAssignee().equals(username) &&
                        task.getProcessInstanceId().equals(processInstanceId)) {
//                    log.info("ProcessInstanceId is {}", task.getProcessInstanceId());
//                    log.info("taskid is {}",task.getId());
                    actFlowCommService.completeProcess("同意", username, task.getId(),"");
                }
            }
        }
        else {
            return Result.error("空任务！");
        }
        return Result.success("上报检验单成功");
    }


}
